<template>
  <div>
    <div v-if="!addBrandDialog">
      <div style="float:left;margin:10px">
        <el-button size="mini" type="primary" @click="openBrandDialog()">添加品牌</el-button>
      </div>

      <el-table
              :data="brandList"
              size="mini"
              border
              :header-cell-style="{background:'#f2f3f7', color: '#333', textAlign: 'center'}"
              style="width: 100%"
      >
        <el-table-column type="index" align="center" label="序号" width="50" :index="indexMethod" />
        <el-table-column prop="name" align="center" label="品牌名称" width="180" />
        <el-table-column prop="brandPicture" align="center" label="品牌logo" width="180" >
          <template slot-scope="scope">
            <el-image
                    style="width: 100px; height: 100px"
                    :src="scope.row.brandPicture"
                    fit="contain"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="品牌介绍" />
        <el-table-column prop="companyName" label="公司名称" />
        <el-table-column label="是否同步商户" width="120" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.synMerchant">
              <el-tag size="mini" type="success">是</el-tag>
            </div>
            <div v-else>
              <el-tag size="mini" type="danger">否</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" />
        <el-table-column prop="remark" label="品牌种类" />
        <el-table-column prop="createTime" align="center" width="180" label="创建时间" />
        <el-table-column label="操作" align="center" width="180">
          <template slot-scope="scope">
            <el-link style="font-size: 13px;" type="primary" @click="editBrand(scope.row)">编辑<i class="el-icon-delete el-icon--right" /></el-link>
            <el-link style="margin-left: 10px;font-size: 13px;" type="primary" @click="delBrand(scope.row.id)">删除<i class="el-icon-delete el-icon--right" /></el-link>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
              small
              style="overflow: auto hidden; height: 32px;float:right;"
              :current-page="page.currPage"
              :page-sizes="[5, 10, 20, 50]"
              :page-size="page.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="page.totalCount"
              @size-change="pageSizeChange"
              @current-change="pageCurrentChange"
      />
    </div>
    <div v-if="addBrandDialog">
      <el-card class="box-card" style="text-align: center">
          <span>{{title}}</span>
      </el-card>
      <el-card class="box-card">
        <el-form  ref="form" :rules="rulesList" :model="addBrandEntity" size="small" label-width="120px">
          <el-form-item label="品牌名称" prop="name"  label-width="120px">
            <el-input v-model="addBrandEntity.name"  size="small" style="width:200px;"></el-input>
          </el-form-item>
          <el-form-item label="品牌介绍" prop="remark" label-width="120px">
            <el-input v-model="addBrandEntity.remark" size="small" style="width:200px;"></el-input>
          </el-form-item>
          <el-form-item label="公司名称" label-width="120px">
            <el-input v-model="addBrandEntity.companyName" size="small" style="width:200px;"></el-input>
          </el-form-item>
          <el-form-item label="品牌种类" label-width="120px">
            <el-input v-model="addBrandEntity.brandType" size="small" style="width:200px;"></el-input>
          </el-form-item>
          <el-form-item label="是否同步商家">
            <el-radio v-model="addBrandEntity.synMerchant" :label=true>是</el-radio>
            <el-radio v-model="addBrandEntity.synMerchant" :label=false>否</el-radio>
          </el-form-item>
          <el-form-item label="排序" label-width="120px">
            <el-input v-model="addBrandEntity.sort" size="small" style="width:200px;"></el-input>
          </el-form-item>
          <el-form-item label="品牌logo">
            <el-upload
                    action=""
                    list-type="picture-card"
                    :on-preview="handlePictureCardPreview"
                    :on-remove="handleRemove"
                    :http-request="ossUpload"
                    :file-list="imgFilesList"
                    :limit="1"
                    :on-exceed="handleExceed"
            >
              <i class="el-icon-plus" />
<!--              <div slot="tip" class="el-upload__tip">分类图片只能上传大小小于200kb文件，且宽高等比例</div>-->
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="addBrandMethod">保存</el-button>
            <el-button  @click="cancel" size="small">取消</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import { productAjax, sysAjax } from 'Ajax'
const axios = require('axios')
const { listBrand, addBrand, updateBrand, delBrandById } = productAjax
export default {
  name: 'ProductBrand',
  components: {},

  data() {
    return {
      // 遮罩层
      loading: true,
      // 单位list
      brandList: [],
      // 添加单位
      addBrandEntity: { name: '' ,synMerchant:false},
      // 添加单位弹出层
      addBrandDialog: false,
      queryData: {
        pageNum: 1,
        pageSize: 10
      },
      type:'add',
      title:'',
      page: {
        currPage: 1,
        pageSize: 10,
        totalCount: 100
      },
      rulesList: {
        name: [{ required: true, message: '请输入品牌名', trigger: 'blur' }],
        remark: [{ required: true, message: '请输入品牌介绍', trigger: 'blur' }]
      },
      dialogImageUrl: '',
      dialogVisible: false,
      imgFilesList: [],
    }
  },
  created() {
    this.getBrandList()
  },
  methods: {
    getBrandList() {
      this.cancel();
      this.loading = true
      listBrand(this.queryData).then(response => {
        this.brandList = response.list
        this.page.currPage = response.currPage
        this.page.pageSize = response.pageSize
        this.page.totalCount = response.totalCount
        this.loading = false
      })
    },
    pageSizeChange(val) {
      this.queryData.pageSize = val
      this.getBrandList()
    },
    pageCurrentChange(val) {
      this.queryData.pageNum = val
      this.getBrandList()
    },
    editBrand(row){
      this.title = "编辑品牌"
      this.type = 'edit'
      this.addBrandDialog = true
      debugger;
      this.addBrandEntity = JSON.parse(JSON.stringify(row))
      if (this.isNotBlank(this.addBrandEntity.brandPicture)) {
        const imgEntity = { url: this.addBrandEntity.brandPicture }
        this.imgFilesList.push(imgEntity)
      }

    },
    delBrand(id) {
      const _this = this
      delBrandById({ brandId: id }).then(response => {
        this.msgSuccess('删除成功')
        _this.getBrandList()
      })
    },
    openBrandDialog() {
      this.title = "新增品牌"
      this.type = 'add'
      this.addBrandDialog = true

    },
    cancel(){
      this.type = 'add'
      this.addBrandDialog = false
      this.addBrandEntity = {name:'',synMerchant:false}
      this.imgFilesList = []
    },
    addBrandMethod() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const _this = this
          if(this.type === 'add'){
            addBrand(this.addBrandEntity).then(response => {
              this.msgSuccess('添加成功')
              this.addBrandDialog = false
              _this.getBrandList()
            })
          }else{
            updateBrand(this.addBrandEntity).then(response => {
              this.msgSuccess('更新成功')
              this.addBrandDialog = false
              _this.getBrandList()
            })
          }


        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    afterBrandDialog() {
      this.addBrandEntity = {}
    },
    indexMethod(index) {
      return index + 1
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
      console.log('url', this.dialogImageUrl)
    },
    beforeAvatarUpload(file) {
      // const width = 1024
      // const height = 1024
      // 上传图片前处理函数
      console.info(file.size)
      const isBig = !(file.size / 1024 >= 200)
      if (!isBig) {
        this.$message.error('上传图片必须小于200kb')
        return false
      }
      const isSize = new Promise(function(resolve, reject) {
        const _URL = window.URL || window.webkitURL
        const image = new Image()
        image.onload = function() {
          const valid = image.width === image.height
          valid ? resolve() : reject()
        }
        image.src = _URL.createObjectURL(file)
      }).then(() => {
                return file
              }, () => {
                this.$message.error('上传图片尺寸不符合,只能是宽高相同的图片')
                return Promise.reject()
              }
      )
      return isSize
    },
    ossUpload(data) {
      const file = data.file
      console.log(file)

      const index = file.name.indexOf('.')
      const nameEnd = file.name.substr(index)

      sysAjax.getOssPolicy().then(res => {
        console.log('policy', res)

        const nameStart = new Date().getTime() + '' + Math.ceil(Math.random() * 100)
        const name = '/' + nameStart + nameEnd

        const sendData = new FormData()
        sendData.append('OSSAccessKeyId', res.accessKeyId)
        sendData.append('policy', res.policy)
        sendData.append('signature', res.signature)
        // sendData.append('keys', res.dir)
        sendData.append('key', res.dir + name)
        sendData.append('success_action_status', '200') // 指定返回的状态码
        sendData.append('callback', res.callback)
        sendData.append('type', 'image/jpeg')
        sendData.append('file', file)
        axios.post(res.host, sendData, {
          'Content-Type': 'multipart/form-data'
        }).then(ossRes => {
          console.log('file', ossRes.data.data)
          console.log('url', ossRes.data.data.filename)
          this.addBrandEntity.brandPicture = ossRes.data.data.filename
        })
      })
    },
    handleExceed(files, fileList) {
      this.$message.warning('商品品牌图片仅限上传一张')
    },
    isBlank(str) {
      if (str === '' || str === null || str === undefined) { // "",null,undefined
        return true
      }
      return false
    },
    isNotBlank(str) {
      if (this.isBlank(str)) {
        return false
      }
      return true
    }
  }
}
</script>

<style scoped>
  .normalForm >>> .el-form-item__label {
    font-weight:normal
  }
</style>
